package com.xiaojun.whut.Entity;

import lombok.Data;
import org.hibernate.annotations.CreationTimestamp;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import javax.persistence.*;
import java.util.*;

@Entity
@Data
//@Table(uniqueConstraints = @UniqueConstraint(columnNames = {"userName","email","phoneNumber"}))
public class User implements UserDetails {

    public enum Sex{
        Boy,Girl;

    }

    @Column(nullable = false,length = 10)
    private String userName;

    @Column(nullable = false)
    private String password;

    @Column(nullable = false,length = 4)
    @Enumerated(EnumType.STRING)
    private Sex sex;

    @Column(nullable = false,length = 20)
    private String collage;


    @Column(nullable = false,length = 20)
    private String email;

    @Id
    @Column(nullable = false,length = 11)
    private String phoneNumber;

    @ManyToMany(fetch = FetchType.EAGER,cascade = CascadeType.ALL)
    @JoinTable(name = "user_role",joinColumns = {@JoinColumn(name = "user_id",referencedColumnName = "phoneNumber")},
            inverseJoinColumns = {@JoinColumn(name = "role_id",referencedColumnName = "role_id")})
    private Set<Role> roles =new HashSet<>();

    @Column(nullable = false)
    private boolean enable;
    @Column(nullable = false)
    private boolean locked;

    @CreationTimestamp
    private Date createTime;

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return enable;
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        List<SimpleGrantedAuthority> authorities=new ArrayList<>();
        for (Role role:roles){
            authorities.add(new SimpleGrantedAuthority(role.getName()));
        }
        return authorities;
    }

    @Override
    public String getUsername() {
        return userName;
    }


    @Override
    public String toString() {
        return "User{" +
                "userName='" + userName + '\'' +
                ", password='" + password + '\'' +
                ", sex=" + sex +
                ", collage='" + collage + '\'' +
                ", email='" + email + '\'' +
                ", phoneNumber='" + phoneNumber + '\'' +
                ", roles=" + roles +
                ", enable=" + enable +
                ", locked=" + locked +
                '}';
    }
}
